package com.io.base.mvp

import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.viewbinding.ViewBinding
import com.io.commoncontrol.dialogs.ProgressDialogEx
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job

/**
 * Activity的基类
 */
abstract class BaseActivity<P : IPresenter, VB : ViewBinding> : AppCompatActivity(), IActivity<VB> {

    protected lateinit var progressDialog: ProgressDialogEx //loading动画

    //此处主要是为了方便子类使用协程
    private var job: Job
    protected var scope: CoroutineScope
    protected lateinit var mViewBinding: VB
    protected var mPresenter: P? = null
    protected val TAG = this::class.java.simpleName

    init {
        job = Job()
        scope = CoroutineScope(job)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        }
        mViewBinding = initView(savedInstanceState)
        mViewBinding?.let {
            setContentView(it.root)
        }
        progressDialog = ProgressDialogEx(this)
        initData(savedInstanceState)
    }

    /**
     * 在onDestroy中
     * 1,关闭正在显示的动画
     * 2,停止协程中正在进行的工作
     */
    override fun onDestroy() {
        super.onDestroy()
        if (progressDialog.isShowing) {
            progressDialog.dismiss()
        }
        if (job.isActive) {
            job.cancel()
        }
        mPresenter?.let {
            it.onDestroy()
        }
    }

    /**
     * 显示loading动画
     */
    fun showLoading() {
        runOnUiThread {
            if (!progressDialog.isShowing) {
                progressDialog.show()
            }
        }
    }

    /**
     * 隐藏loading动画
     */
    fun hideLoading() {
        runOnUiThread {
            if (progressDialog.isShowing) {
                progressDialog.dismiss()
            }
        }
    }

}